package nl.dxn.tunnel.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.internal.EmptyArrays;
import nl.dxn.tunnel.enums.TransferMessageType;
import nl.dxn.tunnel.po.MessageConfig;
import nl.dxn.tunnel.po.TransferMessage;
import nl.dxn.tunnel.serialize.SerializerDispatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 自定义信息编码器
 */
public class MessageEncoder extends MessageToByteEncoder<TransferMessage> {
    private static final Logger logger = LoggerFactory.getLogger(MessageEncoder.class);

    private static final SerializerDispatcher SERIALIZER_DISPATCHER = new SerializerDispatcher();

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, TransferMessage message, ByteBuf out) {
        try {
            TransferMessageType type = message.getType();
            out.writeInt(type.code);

            MessageConfig meta = message.getConfig();
            byte[] metaByte = meta == null ?
                    EmptyArrays.EMPTY_BYTES : SERIALIZER_DISPATCHER.serialize(meta);
            out.writeInt(metaByte.length);
            out.writeBytes(metaByte);

            if (message.getData() != null && message.getData().length > 0) {
                out.writeBytes(message.getData());
            }
        } catch (Exception ex) {
            logger.error("", ex);
            //throw ex;
        }
    }

//    public static ByteBuf convertByteBuf(ByteBuf out,TransferMessage message) throws Exception {
//        if(out == null)
//        {
//            out = Unpooled.buffer();
//        }
//        TransferMessageType type = message.getType();
//        out.writeInt(type.code);
//        out.writeInt(message.getSerializationType());
//
//        MessageConfig meta = message.getConfig();
//        byte[] metaByte = meta == null ?
//                EmptyArrays.EMPTY_BYTES : SERIALIZER_DISPATCHER.serialize(SerializationType.getInstance(message.getSerializationType()), meta);
//        out.writeInt(metaByte.length);
//        out.writeBytes(metaByte);
//
//        if (message.getData() != null && message.getData().length > 0) {
//            out.writeBytes(message.getData());
//        }
//        return out;
//    }
}
